package com.itheima.sfbx.insurance.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.itheima.sfbx.framework.commons.exception.ProjectException;
import com.itheima.sfbx.framework.commons.utils.BeanConv;
import com.itheima.sfbx.framework.commons.utils.EmptyUtil;
import com.itheima.sfbx.framework.commons.utils.ExceptionsUtil;
import com.itheima.sfbx.insurance.constant.SafeguardCacheConstant;
import com.itheima.sfbx.insurance.dto.SafeguardVO;
import com.itheima.sfbx.insurance.enums.SafeguardEnum;
import com.itheima.sfbx.insurance.mapper.SafeguardMapper;
import com.itheima.sfbx.insurance.pojo.Safeguard;
import com.itheima.sfbx.insurance.service.ISafeguardService;
import lombok.extern.slf4j.Slf4j;
import org.jetbrains.annotations.NotNull;
import org.springframework.cache.annotation.CacheEvict;
import org.springframework.cache.annotation.CachePut;
import org.springframework.cache.annotation.Cacheable;
import org.springframework.cache.annotation.Caching;
import org.springframework.stereotype.Service;

import java.util.Arrays;
import java.util.List;
import java.util.function.Function;
import java.util.stream.Collectors;

@Slf4j
@Service
public class SafeguardServiceImpl extends ServiceImpl<SafeguardMapper, Safeguard> implements ISafeguardService {
    @Override
    //value + key 是缓存在缓存组件 (redis) 中的key  --> 一个抽象成, 底层的组件, 可以随意更换, 标记的方法的结果, 进行缓存
    @Cacheable(value = SafeguardCacheConstant.PAGE, key = "#pageNum +'-' +#pageSize+'-'+#safeguardVO.hashCode()")
    public Page<SafeguardVO> findPage(SafeguardVO safeguardVO, int pageNum, int pageSize) {
        try {
            LambdaQueryWrapper<Safeguard> queryWrapper = queryWrapper(safeguardVO);
            //上述查询条件对象对应的sql where order 子句是什么
            //where safeguard_key = ? and safeguard_key_name like ? and data_state = ? order by create_time desc
            //2、查询
            Page<Safeguard> page = new Page<>(pageNum, pageSize);
            Page<Safeguard> safeguardPage = page(page, queryWrapper);
            //3、返回结果
            return BeanConv.toPage(safeguardPage, SafeguardVO.class);
        } catch (Exception e) {
            //将堆栈信息转换为字符串
            log.error("查询保障项列表失败：{}", ExceptionsUtil.getStackTraceAsString(e));

            throw new ProjectException(SafeguardEnum.PAGE_FAIL);
        }
    }

    /**
     * 创建查询条件对象
     *
     * @param safeguardVO
     * @return
     */
    @NotNull
    private static LambdaQueryWrapper<Safeguard> queryWrapper(SafeguardVO safeguardVO) {
        //1、构造查询条件对象
        LambdaQueryWrapper<Safeguard> queryWrapper = new LambdaQueryWrapper<>();
        //保障项编码
        queryWrapper.eq(!EmptyUtil.isNullOrEmpty(safeguardVO.getSafeguardKey()),
                Safeguard::getSafeguardKey, safeguardVO.getSafeguardKey());
        //根据保障项名称,进行模糊查询
        queryWrapper.like(!EmptyUtil.isNullOrEmpty(safeguardVO.getSafeguardKeyName()),
                Safeguard::getSafeguardKeyName, safeguardVO.getSafeguardKeyName());
        //数据状态
        queryWrapper.eq(!EmptyUtil.isNullOrEmpty(safeguardVO.getDataState()), Safeguard::getDataState, safeguardVO.getDataState());

        //根据创建时间降序排序
        queryWrapper.orderByDesc(Safeguard::getCreateTime);
        return queryWrapper;
    }

    @Override
    @Cacheable(value = SafeguardCacheConstant.BASIC, key = "#safeguardId")
    public SafeguardVO findById(String safeguardId) {
        Safeguard safeguard = getById(safeguardId);
        return BeanConv.toBean(safeguard, SafeguardVO.class);
    }

    @Override
    @Caching(evict = {
            @CacheEvict(value = SafeguardCacheConstant.PAGE, allEntries = true),
            @CacheEvict(value = SafeguardCacheConstant.LIST, allEntries = true)
    },
            put = {@CachePut(value = SafeguardCacheConstant.BASIC, key = "#result.safeguardId")}
    )
    public SafeguardVO save(SafeguardVO safeguardVO) {
        try {
            //转换为实体类
            Safeguard safeguard = BeanConv.toBean(safeguardVO, Safeguard.class);
            //保存数据; mp
            boolean flag = save(safeguard);
            //判断是否保存成功
            if (!flag) {
                throw new RuntimeException("新建保障项失败");
            }
            //返回结果
            return BeanConv.toBean(safeguard, SafeguardVO.class);
        } catch (RuntimeException e) {
            //ExceptionsUtil.getStackTraceAsString(e) 将堆栈信息转为字符串
            log.error("新建保障项失败：{}", ExceptionsUtil.getStackTraceAsString(e));

            throw new ProjectException(SafeguardEnum.SAVE_FAIL);
        }
    }

    @Override
    @Caching(evict = {
            @CacheEvict(value = SafeguardCacheConstant.PAGE, allEntries = true),
            @CacheEvict(value = SafeguardCacheConstant.LIST, allEntries = true),
            @CacheEvict(value = SafeguardCacheConstant.BASIC, key = "#safeguardVO.id")  // 只删除一天数据, 就是更新的那一条
    })
    public Boolean update(SafeguardVO safeguardVO) {

        try {
            //1、将VO转换为实体类
            Safeguard safeguard = BeanConv.toBean(safeguardVO, Safeguard.class);
            //2、进行修改
            boolean flag = updateById(safeguard);
            //3、判断是否修改成功
            if (!flag) {
                throw new RuntimeException("修改保障项失败");
            }
            //4、返回结果
            return flag;
        } catch (RuntimeException e) {
            log.error("修改保障项失败：{}", ExceptionsUtil.getStackTraceAsString(e));
            throw new ProjectException(SafeguardEnum.UPDATE_FAIL);
        }


    }

    @Override
    @Caching(evict = {
            @CacheEvict(value = SafeguardCacheConstant.PAGE, allEntries = true),
            @CacheEvict(value = SafeguardCacheConstant.LIST, allEntries = true),
            @CacheEvict(value = SafeguardCacheConstant.BASIC, allEntries = true)
    })
    public Boolean delete(String[] checkedIds) {
        try {
            //1、将字符串数组转换为Long集合
            List<Long> idsList = Arrays.asList(checkedIds).stream().map(Long::valueOf).collect(Collectors.toList());
            //下面是详细解释
//        List<String> list = Arrays.asList(checkedIds);  是String类型, 需要转换成L唵类型
//        List<Long> idsList = Arrays.asList(checkedIds).stream().map(
//                new Function<String, Long>() {
//                    @Override
//                    public Long apply(String s) {
//                        return Long.valueOf(s);
//                    }
//                }
//        ).collect(Collectors.toList());
            //进行删除
            boolean flag = removeByIds(idsList);
            //判断是否删除成功
            if (!flag) {
                throw new RuntimeException("删除保障项失败");
            }
            //返回操作结果
            return flag;
        } catch (RuntimeException e) {
            log.error("删除保障项失败：{}", ExceptionsUtil.getStackTraceAsString(e));
            throw new ProjectException(SafeguardEnum.DEL_FAIL);
        }
    }

    @Override
    @Cacheable(value = SafeguardCacheConstant.LIST, key = "#safeguardVO.hashCode()")
    public List<SafeguardVO> findList(SafeguardVO safeguardVO) {
        try {
            //1、创建查询条件对象  --->便于后面复用
            LambdaQueryWrapper<Safeguard> queryWrapper = queryWrapper(safeguardVO);
            //2、查询列表
            List<Safeguard> list = list(queryWrapper);
            //3、将实体类列表转换为VO列表
            List<SafeguardVO> listVO = BeanConv.toBeanList(list, SafeguardVO.class);
            return listVO;
        } catch (Exception e) {
            log.error("查询保障项列表失败：{}", ExceptionsUtil.getStackTraceAsString(e));
            throw new ProjectException(SafeguardEnum.LIST_FAIL);
        }
    }

    @Override
    public List<SafeguardVO> findShowPageItemByKey(List<String> safeguardKeyList) {
        return List.of();
    }

    @Override
    public SafeguardVO findBySafeguardKey(String safeguardKey) {
        return null;
    }
}